<template>
  <div class="el-date-range-picker">
    <div 
      class="el-date-range-picker__input-wrapper"
      @click="togglePicker"
    >
      <div class="el-date-range-picker__input-content">
        <span v-if="!localStartDate && !localEndDate" class="el-date-range-picker__placeholder">
          选择日期范围
        </span>
        <span v-else class="el-date-range-picker__text">
          {{ localStartDate || '开始日期' }} 至 {{ localEndDate || '结束日期' }}
        </span>
      </div>
      <div class="el-date-range-picker__icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
          <line x1="16" y1="2" x2="16" y2="6"></line>
          <line x1="8" y1="2" x2="8" y2="6"></line>
          <line x1="3" y1="10" x2="21" y2="10"></line>
        </svg>
      </div>
    </div>

    <div v-if="isPickerOpen" class="el-date-range-picker__dropdown">
      <div class="el-date-range-picker__content">
        <div class="el-date-range-picker__shortcuts">
          <div
            v-for="option in quickOptions"
            :key="option.key"
            :class="['el-date-range-picker__shortcut', { active: isActiveOption(option.key) }]"
            @click="selectQuickOption(option.key)"
          >
            {{ option.label }}
          </div>
        </div>
        
        <div class="el-date-range-picker__calendars">
          <div class="el-date-range-picker__calendar">
            <div class="el-date-range-picker__calendar-header">
              <button @click="prevMonth" class="el-date-range-picker__calendar-btn">
                &lt;
              </button>
              <span>{{ formatCalendarHeader(startCalendarDate) }}</span>
              <button @click="nextMonth" class="el-date-range-picker__calendar-btn">
                &gt;
              </button>
            </div>
            <div class="el-date-range-picker__calendar-body">
              <div class="el-date-range-picker__weekdays">
                <div v-for="day in weekDays" :key="day" class="el-date-range-picker__weekday">
                  {{ day }}
                </div>
              </div>
              <div class="el-date-range-picker__days">
                <div
                  v-for="day in calendarDays"
                  :key="day.date"
                  :class="[
                    'el-date-range-picker__day',
                    {
                      'is-in-range': isInRange(day.date),
                      'is-start': isStartDate(day.date),
                      'is-end': isEndDate(day.date),
                      'is-disabled': isDisabled()
                    }
                  ]"
                  @click="selectDate(day.date)"
                >
                  {{ day.day }}
                </div>
              </div>
            </div>
          </div>
          
          <div class="el-date-range-picker__calendar">
            <div class="el-date-range-picker__calendar-header">
              <button @click="nextMonth" class="el-date-range-picker__calendar-btn">
                &lt;
              </button>
              <span>{{ formatCalendarHeader(endCalendarDate) }}</span>
              <button @click="nextMonth" class="el-date-range-picker__calendar-btn">
                &gt;
              </button>
            </div>
            <div class="el-date-range-picker__calendar-body">
              <div class="el-date-range-picker__weekdays">
                <div v-for="day in weekDays" :key="day" class="el-date-range-picker__weekday">
                  {{ day }}
                </div>
              </div>
              <div class="el-date-range-picker__days">
                <div
                  v-for="day in endCalendarDays"
                  :key="day.date"
                  :class="[
                    'el-date-range-picker__day',
                    {
                      'is-in-range': isInRange(day.date),
                      'is-start': isStartDate(day.date),
                      'is-end': isEndDate(day.date),
                      'is-disabled': isDisabled()
                    }
                  ]"
                  @click="selectDate(day.date)"
                >
                  {{ day.day }}
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="el-date-range-picker__footer">
          <button class="el-date-range-picker__btn el-date-range-picker__btn--cancel" @click="closePicker">
            取消
          </button>
          <button class="el-date-range-picker__btn el-date-range-picker__btn--confirm" @click="confirmSelection">
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { formatDateInTimeZone, getTimeZone } from '@/utils/dateUtils'

interface Props {
  startDate?: string
  endDate?: string
}

interface Emits {
  (e: 'update:startDate', value: string | undefined): void
  (e: 'update:endDate', value: string | undefined): void
  (e: 'change', startDate: string | undefined, endDate: string | undefined): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const localStartDate = ref<string>('')
const localEndDate = ref<string>('')
const activeQuickOption = ref<string>('')
const isPickerOpen = ref<boolean>(false)
const startCalendarDate = ref<Date>(new Date())
const endCalendarDate = ref<Date>(new Date())
const tempStartDate = ref<string>('')
const tempEndDate = ref<string>('')

// 常量
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 快捷选项
const quickOptions = [
  { key: 'today', label: '今天', getRange: () => getTodayRange() },
  { key: 'yesterday', label: '昨天', getRange: () => getYesterdayRange() },
  { key: 'thisWeek', label: '本周', getRange: () => getThisWeekRange() },
  { key: 'lastWeek', label: '上周', getRange: () => getLastWeekRange() },
  { key: 'thisMonth', label: '本月', getRange: () => getThisMonthRange() },
  { key: 'lastMonth', label: '上月', getRange: () => getLastMonthRange() },
  { key: 'thisYear', label: '今年', getRange: () => getThisYearRange() },
  { key: 'lastYear', label: '去年', getRange: () => getLastYearRange() },
]

// 计算属性
const isActiveOption = (key: string) => {
  return activeQuickOption.value === key
}

const calendarDays = computed(() => {
  return getCalendarDays(startCalendarDate.value)
})

const endCalendarDays = computed(() => {
  return getCalendarDays(endCalendarDate.value)
})

// 日期选择器方法
const togglePicker = () => {
  isPickerOpen.value = !isPickerOpen.value
  if (isPickerOpen.value) {
    tempStartDate.value = localStartDate.value
    tempEndDate.value = localEndDate.value
    initializeCalendars()
  }
}

const closePicker = () => {
  isPickerOpen.value = false
  localStartDate.value = tempStartDate.value
  localEndDate.value = tempEndDate.value
}

const confirmSelection = () => {
  isPickerOpen.value = false
  emitDates()
}

const initializeCalendars = () => {
  const now = new Date()
  startCalendarDate.value = new Date(now.getFullYear(), now.getMonth(), 1)
  endCalendarDate.value = new Date(now.getFullYear(), now.getMonth() + 1, 1)
}

const prevMonth = () => {
  const newDate = new Date(startCalendarDate.value)
  newDate.setMonth(newDate.getMonth() - 1)
  startCalendarDate.value = newDate
  
  const newEndDate = new Date(endCalendarDate.value)
  newEndDate.setMonth(newEndDate.getMonth() - 1)
  endCalendarDate.value = newEndDate
}

const nextMonth = () => {
  const newDate = new Date(startCalendarDate.value)
  newDate.setMonth(newDate.getMonth() + 1)
  startCalendarDate.value = newDate
  
  const newEndDate = new Date(endCalendarDate.value)
  newEndDate.setMonth(newEndDate.getMonth() + 1)
  endCalendarDate.value = newEndDate
}

const formatCalendarHeader = (date: Date) => {
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
}

const getCalendarDays = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth()
  const firstDay = new Date(year, month, 1)
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())
  
  const days = []
  const current = new Date(startDate)
  
  for (let i = 0; i < 42; i++) {
    days.push({
      date: formatDateInTimeZone(new Date(current), getTimeZone()),
      day: current.getDate(),
      isCurrentMonth: current.getMonth() === month
    })
    current.setDate(current.getDate() + 1)
  }
  
  return days
}

const selectDate = (date: string) => {
  if (!localStartDate.value || (localStartDate.value && localEndDate.value)) {
    localStartDate.value = date
    localEndDate.value = ''
  } else if (date >= localStartDate.value) {
    localEndDate.value = date
  } else {
    localEndDate.value = localStartDate.value
    localStartDate.value = date
  }
  
  activeQuickOption.value = ''
}

const isInRange = (date: string) => {
  if (!localStartDate.value || !localEndDate.value) return false
  return date >= localStartDate.value && date <= localEndDate.value
}

const isStartDate = (date: string) => {
  return date === localStartDate.value
}

const isEndDate = (date: string) => {
  return date === localEndDate.value
}

const isDisabled = () => {
  return false // 可以根据需要添加禁用逻辑
}

const emitDates = () => {
  activeQuickOption.value = ''
  emit('update:startDate', localStartDate.value || undefined)
  emit('update:endDate', localEndDate.value || undefined)
  emit('change', localStartDate.value || undefined, localEndDate.value || undefined)
}

const selectQuickOption = (key: string) => {
  const option = quickOptions.find(opt => opt.key === key)
  if (option) {
    const { startDate, endDate } = option.getRange()
    localStartDate.value = startDate
    localEndDate.value = endDate
    activeQuickOption.value = key
    
    emit('update:startDate', startDate)
    emit('update:endDate', endDate)
    emit('change', startDate, endDate)
  }
}

// 日期范围计算函数
const getTodayRange = () => {
  const today = new Date()
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(today, timeZone),
    endDate: formatDateInTimeZone(today, timeZone)
  }
}

const getYesterdayRange = () => {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(yesterday, timeZone),
    endDate: formatDateInTimeZone(yesterday, timeZone)
  }
}

const getThisWeekRange = () => {
  const today = new Date()
  const dayOfWeek = today.getDay()
  const startOfWeek = new Date(today)
  startOfWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)) // 周一开始
  const endOfWeek = new Date(startOfWeek)
  endOfWeek.setDate(startOfWeek.getDate() + 6)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfWeek, timeZone),
    endDate: formatDateInTimeZone(endOfWeek, timeZone)
  }
}

const getLastWeekRange = () => {
  const today = new Date()
  const dayOfWeek = today.getDay()
  const startOfLastWeek = new Date(today)
  startOfLastWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1) - 7)
  const endOfLastWeek = new Date(startOfLastWeek)
  endOfLastWeek.setDate(startOfLastWeek.getDate() + 6)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfLastWeek, timeZone),
    endDate: formatDateInTimeZone(endOfLastWeek, timeZone)
  }
}

const getThisMonthRange = () => {
  const today = new Date()
  const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
  const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfMonth, timeZone),
    endDate: formatDateInTimeZone(endOfMonth, timeZone)
  }
}

const getLastMonthRange = () => {
  const today = new Date()
  const startOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1)
  const endOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfLastMonth, timeZone),
    endDate: formatDateInTimeZone(endOfLastMonth, timeZone)
  }
}

const getThisYearRange = () => {
  const today = new Date()
  const startOfYear = new Date(today.getFullYear(), 0, 1)
  const endOfYear = new Date(today.getFullYear(), 11, 31)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfYear, timeZone),
    endDate: formatDateInTimeZone(endOfYear, timeZone)
  }
}

const getLastYearRange = () => {
  const today = new Date()
  const startOfLastYear = new Date(today.getFullYear() - 1, 0, 1)
  const endOfLastYear = new Date(today.getFullYear() - 1, 11, 31)
  
  const timeZone = getTimeZone()
  return {
    startDate: formatDateInTimeZone(startOfLastYear, timeZone),
    endDate: formatDateInTimeZone(endOfLastYear, timeZone)
  }
}

// 监听props变化
watch(() => props.startDate, (newVal) => {
  if (newVal !== localStartDate.value) {
    localStartDate.value = newVal || ''
    activeQuickOption.value = ''
  }
})

watch(() => props.endDate, (newVal) => {
  if (newVal !== localEndDate.value) {
    localEndDate.value = newVal || ''
    activeQuickOption.value = ''
  }
})

// 初始化
onMounted(() => {
  localStartDate.value = props.startDate || ''
  localEndDate.value = props.endDate || ''
})
</script>

<style lang="scss" scoped>
.el-date-range-picker {
  position: relative;
  display: inline-block;
  width: 100%;
  max-width: 400px;
}

.el-date-range-picker__input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-border-color-light);
  }
  
  &:focus-within {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }
}

.el-date-range-picker__input-content {
  flex: 1;
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.el-date-range-picker__placeholder {
  color: var(--el-text-color-placeholder);
}

.el-date-range-picker__text {
  color: var(--el-text-color-primary);
}

.el-date-range-picker__icon {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
  
  svg {
    width: 16px;
    height: 16px;
  }
}

.el-date-range-picker__dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4px;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  z-index: 1000;
  min-width: 540px;
}

.el-date-range-picker__content {
  display: flex;
  flex-direction: column;
}

.el-date-range-picker__shortcuts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.el-date-range-picker__shortcut {
  padding: 4px 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  border-radius: var(--el-border-radius-small);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: var(--el-bg-color);
    color: var(--el-color-primary);
  }
  
  &.active {
    background: var(--el-color-primary);
    color: var(--el-text-color-primary);
  }
}

.el-date-range-picker__calendars {
  display: flex;
  padding: 16px;
}

.el-date-range-picker__calendar {
  flex: 1;
  min-width: 240px;
}

.el-date-range-picker__calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid var(--el-border-color-light);
}

.el-date-range-picker__calendar-btn {
  background: none;
  border: none;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  padding: 4px 8px;
  border-radius: var(--el-border-radius-small);
  transition: all 0.3s ease;
  
  &:hover {
    background: var(--el-bg-color);
    color: var(--el-text-color-primary);
  }
}

.el-date-range-picker__calendar-body {
  padding: 8px;
}

.el-date-range-picker__weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  margin-bottom: 8px;
}

.el-date-range-picker__weekday {
  text-align: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  font-weight: 500;
  padding: 4px;
}

.el-date-range-picker__days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.el-date-range-picker__day {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  font-size: 12px;
  color: var(--el-text-color-primary);
  border-radius: var(--el-border-radius-small);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: var(--el-bg-color);
  }
  
  &.is-in-range {
    background: var(--el-color-primary);
    opacity: 0.1;
    color: var(--el-text-color-primary);
  }
  
  &.is-start,
  &.is-end {
    background: var(--el-color-primary);
    color: var(--el-text-color-primary);
    font-weight: 500;
  }
  
  &.is-disabled {
    color: var(--el-text-color-placeholder);
    cursor: not-allowed;
    opacity: 0.5;
  }
}

.el-date-range-picker__footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-light);
}

.el-date-range-picker__btn {
  padding: 6px 16px;
  font-size: 12px;
  border-radius: var(--el-border-radius-small);
  border: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: var(--el-bg-color-overlay);
  }
}

.el-date-range-picker__btn--cancel {
  &:hover {
    color: var(--el-color-danger);
  }
}

.el-date-range-picker__btn--confirm {
  background: var(--el-color-primary);
  color: var(--el-text-color-primary);
  border-color: var(--el-color-primary);
  
  &:hover {
    background: var(--el-color-primary-light-3);
    opacity: 0.9;
  }
}

@media (max-width: 768px) {
  .el-date-range-picker {
    max-width: 100%;
  }
  
  .el-date-range-picker__dropdown {
    min-width: auto;
    max-width: 100vw;
  }
  
  .el-date-range-picker__calendars {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-date-range-picker__shortcuts {
    justify-content: center;
  }
}
</style>